﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using RRQMSocket;
using RRQMSocketServer.controller;

namespace RRQMSocketServer.server
{
    class VIPTcpService : TcpService<VIPTcpSocketClient>
    {

        private Dictionary<string, BaseController> controllerDic = new Dictionary<string, BaseController>();

        public VIPTcpService() {
            InitController();
        }

        protected override void OnCreateSocketCliect(VIPTcpSocketClient socketClient, CreateOption createOption)
        {
            if (createOption.NewCreate) {
                socketClient.SetDataHandlingAdapter(new FixedHeaderDataHandlingAdapter());
            }
        }

        private void InitController() {
            controllerDic.Add("User", new UserController());
        }

        /// <summary>
        /// 处理数据
        /// </summary>
        /// <param name="data"></param>
        public void HandleRequest(string data,VIPTcpSocketClient vipTcpSocketClient) {
            string[] strArr = data.Split('|');
            string requestCode = strArr[0];
            string actionCode = strArr[1];
            string handlerData = strArr[2];
            BaseController controller;
            bool dic = controllerDic.TryGetValue(requestCode, out controller);
            if (!dic)
            {
                string msg = "[" + requestCode + "]处理器未找到";
                SocketBaseFramwork.Instance.AddLog(msg);
                return;
            }
            MethodInfo mi = controller.GetType().GetMethod(actionCode);
            if (mi == null)
            {
                string msg = "[" + controller.GetType().Name + "]中没有对应的处理方法:[" + actionCode + "]";
                SocketBaseFramwork.Instance.AddLog(msg);
                return;
            }
            object[] parameters = new object[] { handlerData, this };
            object o = mi.Invoke(controller, parameters);
            if (o == null || string.IsNullOrEmpty(o as string))
            {
                return;
            }
            string res = actionCode + '|' + o;
            byte[] byteData = Encoding.UTF8.GetBytes(res);
            vipTcpSocketClient.Send(byteData);
        }

    }
}
